//
//  MyCollectViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/7/20.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MyCollectViewController.h"
#import "StoneStreetTableViewCell.h"
#import "MineTableViewCell.h"
#import "CommitStarsView.h"
#import "StoneStreetStoreDetailViewController.h"
#import "StoneShowDetailViewController.h"
static NSString *cellIdentifier = @"StoneStreetTableViewCell";
static NSString *CellIdentifier = @"MineTableViewCell";
@interface MyCollectViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (weak, nonatomic) IBOutlet UIView *buttonView;
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *stoneButton;
@property (weak, nonatomic) IBOutlet UIButton *mineButton;
@property(nonatomic,strong)NSMutableArray * collectArray;
@end

@implementation MyCollectViewController

- (void)viewWillAppear:(BOOL)animated{
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _collectArray = [NSMutableArray array];
    // Do any additional setup after loading the view.
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.buttonView];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:cellIdentifier bundle:nil] forCellReuseIdentifier:cellIdentifier];
    
    [self.tableView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    
    
}

- (IBAction)back:(id)sender {
    [self backBtn];
    
}


- (IBAction)changeCollect:(UIButton *)sender {
    sender.selected = YES;
    if (sender == _stoneButton) {
        _mineButton.selected = NO;
    }else{
        _stoneButton.selected = NO;
    }
    [_collectArray removeAllObjects];
    [self.tableView.header beginRefreshing];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getCollectList];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.collectArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getCollectList];
        });
    }
    
}

#pragma mark === 获取收藏列表(商家、矿山)
- (void)getCollectList{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"page"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    
    self.shareApi.delegate=self;
    if (_stoneButton.selected) {//石材商
         [self.shareApi  requestOperationWithDic:dic withPath:GS_myMallCollectStoreList withHttpType:@"POST" withTag:GS_GS_myMallCollectStoreList];
    }else{//矿主
        [self.shareApi  requestOperationWithDic:dic withPath:GS_queryCollectStoreForeignList withHttpType:@"POST" withTag:GS_GS_queryCollectStoreForeignList];
    }
   
}




#pragma mark  ==== tableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _collectArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_stoneButton.selected) {
    return 96*VerticalRatio();
    }else{
    return 88*VerticalRatio();
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_stoneButton.selected) {
        StoneStreetTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[StoneStreetTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }

        NSDictionary * dic = _collectArray[indexPath.row][@"mallStore"];
        cell.storeName.text = [NSString stringWithFormat:@"%@",dic[@"mstoName"]];
        cell.storePhone.text = [NSString stringWithFormat:@"%@",dic[@"mstoPhone"]];
        cell.storeAddress.text = [NSString stringWithFormat:@"%@",dic[@"mstoAddress"]];
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"mstoImage"]];
        if (image.length>0) {
            [cell.storeImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        
        cell.attestImage.hidden = YES;
        NSString * attest = [NSString stringWithFormat:@"%@",dic[@"mstoIsCert"]];
        if ([attest isEqualToString:@"2"]) {
            cell.attestImage.hidden = NO;
            CGSize size = [cell.storeName.text sizeWithFont:cell.storeName.font];
            cell.attestImage.frame = CGRectMake(85*VerticalRatio()+size.width, 11*VerticalRatio(), 18*VerticalRatio(), 13*VerticalRatio());
        }
        
        CGFloat starts = 0;
        if (![dic[@"mstoCredit"] isEqual:[NSNull null]]) {
           starts =[dic[@"mstoCredit"]floatValue];
        }
        
        CommitStarsView * startView = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(140, 63, 70, 10), NO) SmallStars:starts];
        [cell addSubview:startView];
        
        return cell;
    }else{
        MineTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[MineTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        NSDictionary * dic = _collectArray[indexPath.row][@"mallStoreForeign"];
        
        cell.stoneName.text = [NSString stringWithFormat:@"%@",dic[@"msfoName"]];
        cell.stoneIntro.text = [NSString stringWithFormat:@"%@",dic[@"msfoFeature"]];
        cell.stoneProduct.text = [NSString stringWithFormat:@"%@",dic[@"msfoProduct"]];
        
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"mstoImage"]];
        if (image.length) {
            [cell.stoneImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        
        return cell;
    }
    

    return nil;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_stoneButton.selected) {
        UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        StoneStreetStoreDetailViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"StoneStreetStoreDetail"];
        page.storeId = _collectArray[indexPath.row][@"mallStore"][@"mstoId"];
        [[Common getNavigation]pushViewController:page];
    }else{
        UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        StoneShowDetailViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"StoneShowDetail"];
        page.stoneId = _collectArray[indexPath.row][@"mallStoreForeign"][@"msfoId"];
        [[Common getNavigation]pushViewController:page];
    }
   
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==GS_GS_myMallCollectStoreList||tag ==GS_GS_queryCollectStoreForeignList) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            _totle = [database[@"result"][@"total"] integerValue];
                            if (_totle > PageSize) {
                                __weak __typeof(self) weakSelf = self;
                                if (!self.tableView.footer) {
                                    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                                    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                                        [weakSelf loadMoreData];
                                    }];
                                }
                            }
            if (self.pageNO == 1) {
                [self.collectArray removeAllObjects];
            }
            NSArray *arr = database[@"result"][@"rows"];
            for (id entity in arr) {
                [self.collectArray addObject:entity];
            }
            
            [_tableView reloadData];
            
            });
            
        }
        
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    [self dismissWaitDialog];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
